import { defineStore } from "pinia"
import { LoginType, login , UserInfoType , getUserInfo} from '@/api/login/index'


interface UserStoreType{
    token:string,
    userInfo:UserInfoType
}


let user = defineStore("User",{
    state:():UserStoreType=>{
        return {
            token:sessionStorage.getItem("token") || '',
            userInfo:{
                name:sessionStorage.getItem("name") || '',
                avatarUrl: sessionStorage.getItem("avatarUrl") ||''
            }
        }
    },
    getters:{

    },
    actions:{
         //写登录,因为token相关的数据都可以写到actions
         async doLogin(loginForm:LoginType){
             // {code,message ,data}
             let {code,data} = await login(loginForm);
             if(code==200){
                this.token = data;
                sessionStorage.setItem("token",data);
                //调用查询用户信息
                this.doGetUserInfo();
             }
         },
         async doGetUserInfo(){
            let {code,data} = await getUserInfo(); //http
            if(code == 200){
                this.userInfo = data;
                sessionStorage.setItem("name",data.name);
                sessionStorage.setItem("avatarUrl",data.avatarUrl);
            }
         },
         doLogout(){
            //1.清空
            this.token = '';
            this.userInfo.name = '';
            this.userInfo.avatarUrl = '';
            sessionStorage.removeItem("name");
            sessionStorage.removeItem("token");
            sessionStorage.removeItem("avatarUrl");
         }
    }
});


export default user;